package com.rpay.common.util.http.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ParamUtil {

    /**
     * 检测url是否含有参数，如果有，则把参数加到参数列表中
     *
     * @param url 资源地址
     * @param nvps	参数列表
     * @return	返回去掉参数的url
     * @throws UnsupportedEncodingException
     */
    public static String checkHasParas(String url, List<NameValuePair> nvps, String encoding) throws UnsupportedEncodingException {
        // 检测url中是否存在参数
        if (url.contains(Constants.PARAMETER_START) && url.indexOf(Constants.PARAMETER_START) < url.indexOf(Constants.PARAMETER_EQUAL)) {
            Map<String, Object> map = buildParas(url.substring(url
                    .indexOf(Constants.PARAMETER_START) + 1));
            map2HttpEntity(nvps, map,null,encoding);
            url = url.substring(0, url.indexOf(Constants.PARAMETER_START));
        }
        return url;
    }

    /**
     * 参数转换，将map中的参数，转到参数列表中
     *
     * @param nameValuePairs				参数列表
     * @param formMap				参数列表（map）
     * @throws UnsupportedEncodingException
     */
    public static HttpEntity map2HttpEntity(List<NameValuePair> nameValuePairs, Map<String, Object> formMap,String body, String encoding) throws UnsupportedEncodingException {
        HttpEntity entity = null;
        boolean isSpecial = false;
        // form parameter
        if(formMap!=null && formMap.size()>0){
            // 拼接参数
            for (Map.Entry<String, Object> entry : formMap.entrySet()) {
                    isSpecial = true;
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }
        }
        // request body
        if(body!=null && !body.isEmpty()){
            isSpecial = true;
            entity = new StringEntity(body, encoding);
        }
        if(!isSpecial) {
            entity = new UrlEncodedFormEntity(nameValuePairs, encoding);
        }
        return entity;
    }

    /**
     * map convert to string   & concat
     * @param param
     * @return
     */
    public static String convertStringMap(Map<String, String> param) {
        StringBuffer sb = new StringBuffer();
        if(param != null) {
            for (String key: param.keySet()) {
                sb.append(key+Constants.PARAMETER_EQUAL+param.get(key)+Constants.PARAMETER_SPLITOR);
            }
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }

    /**
     * get 参数填充
     * @param url url
     * @param map map
     * @return string
     */
    public static String buildParas(String url,Map<String, String> map) throws URISyntaxException {
        if (url != null && !"".equals(url)) {
            URI uri = new URI(url);
            // get参数为空
            if (uri.getQuery() == null) {
                return url + Constants.PARAMETER_START + ParamUtil.convertStringMap(map);
            } else {
                return url + Constants.PARAMETER_SPLITOR + ParamUtil.convertStringMap(map);
            }
        }
        return url;
    }

    public static String format(String input, Map<String, String> map) {
        // 遍历map,用value替换掉key
        for (Map.Entry<String, String> entry : map.entrySet()) {
            input = input.replace("{"+entry.getKey()+"}", entry.getValue());
        }
        return input;
    }

    /**
     * 生成参数
     * 参数格式“k1=v1&k2=v2”
     *
     * @param paras				参数列表
     * @return						返回参数列表（map）
     */
    public static Map<String,Object> buildParas(String paras){
        String[] p = paras.split(Constants.PARAMETER_SPLITOR);
        String[][] ps = new String[p.length][2];
        int pos = 0;
        for (int i = 0; i < p.length; i++) {
            pos = p[i].indexOf(Constants.PARAMETER_START);
            ps[i][0]=p[i].substring(0,pos);
            ps[i][1]=p[i].substring(pos+1);
            pos = 0;
        }
        return buildParas(ps);
    }

    /**
     * 生成参数
     * 参数类型：{{"k1","v1"},{"k2","v2"}}
     *
     * @param paras 				参数列表
     * @return						返回参数列表（map）
     */
    public static Map<String,Object> buildParas(String[][] paras){
        // 创建参数队列
        Map<String,Object> map = new HashMap<>(16);
        for (String[] para: paras) {
            map.put(para[0], para[1]);
        }
        return map;
    }

}
